package cevent.source.cloudcenter.business.controller.exception;/**
 * Created by Cevent on 2021/3/20.
 */

import cevent.source.cloudcenter.server.dto.ResponseDataDto;
import cevent.source.cloudcenter.server.exception.BusinessException;
import cevent.source.cloudcenter.server.exception.ValidatorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author cevent
 * @description 控制层异常处理
 * controller异常捕获：需要添加ControllerAdvice
 * responseBody返回json格式的数据
 * exceptionHandler：统一异常处理方法 抛出的异常
 * @date 2021/3/20 10:08
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger LOG= LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler(value=ValidatorException.class)
    @ResponseBody
    public ResponseDataDto validatorExceptionHandler(ValidatorException validatorException){
        ResponseDataDto responseData=new ResponseDataDto();
        responseData.setSuccess(false);
        responseData.setResponseMsg(validatorException.getMessage());
        LOG.warn(validatorException.getMessage());
        //前端通过非法途径发出请求，不给予真实的校验返回值
        //responseData.setResponseMsg("请求非法，请进入浏览器CEVENT-CMS系统后操作");
        return responseData;
    }
    //增加全局捕获business，如果其他模块，直接将这个类复制，引用对应的自定义exception即可
    @ExceptionHandler(value= BusinessException.class)
    @ResponseBody
    public ResponseDataDto businessExceptionHandler(BusinessException businessException){
        ResponseDataDto responseData=new ResponseDataDto();
        //设置返回的参数
        responseData.setSuccess(false);
        responseData.setResponseMsg(businessException.getMessage());
        //业务异常使用error，根据异常处理类返回响应异常描述
        LOG.error("业务登录异常：{}",businessException.getBusinessExceptionCode().getDesc());
        //前端通过非法途径发出请求，不给予真实的校验返回值
        responseData.setResponseMsg(businessException.getBusinessExceptionCode().getDesc());
        return responseData;
    }
}
